﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using TypeResolve;
using XcoAppSpaces.Core;
using testServer.XcoAppSpaces.SL;
using Microsoft.Ccr.Core;

namespace testApp.XcoAppSpaces.SL
{
	public partial class MainPage : UserControl
	{
		private readonly string hostname = "localhost";
		private const int port = 4505;

		private XcoAppSpace space;
		private Port<SpaceMessage> worker;

		private Random random = new Random();

		public MainPage()
		{
			InitializeComponent();
			space = new XcoAppSpace("tcp.port=0");

		}

		private void btConnect_Click(object sender, RoutedEventArgs e)
		{
			btConnect.IsEnabled = false;
			try
			{
				worker = space.Connect<SpaceMessage>(hostname + ":" + port);
				btSendMessage.IsEnabled = true;
			}
			catch (Exception ex)
			{
				lbStatus.Items.Add("Connect Error: " + ex.Message);
				btConnect.IsEnabled = true;
			}
		}

		private void btSendMessage_Click(object sender, RoutedEventArgs e)
		{
			var num1 = random.Next(0, 100);
			var num2 = random.Next(0, 100);

			var msgStatus = new MessageStatus
			{
				Request = num1 + " + " + num2,
				Response = "",
				Progress = 0
			};

			lbStatus.Items.Add(msgStatus);

			var responsePort = space.Receive<double>(m => msgStatus.Response = m.ToString(), SyncContext.UseCurrentSyncContext);
			var progressPort = space.Receive<double>(p => msgStatus.Progress = p, SyncContext.UseCurrentSyncContext);
			
			worker.Post(new SpaceMessage { Num1 = num1, Num2 = num2, ProgressPort = progressPort, ResponsePort = responsePort });
		}
	}
}
